import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import cache from '@/utils/cache'
import { hideLoading, translateRequest } from "@/utils/loading";

// axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL as any,
    timeout: 60000,
    headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})

// 请求拦截器
service.interceptors.request.use(
    (config: any) => {
        translateRequest(config);
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token.replace(/\"/ig, "")}`
        }

        config.headers['Accept-Language'] = cache.getLanguage()

        // 追加时间戳，防止GET请求缓存
        if (config.method?.toUpperCase() === 'GET') {
            config.params = { ...config.params, t: new Date().getTime() }
        }

        if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {
            config.data = qs.stringify(config.data)
        }

        return config
    },
    error => {
        hideLoading();
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response: any) => {
        hideLoading();
        // console.log('response：', response);
        if (response.status !== 200) {
            // 错误提示
            ElMessage.error(response.data.error)
            // 没有权限，如：未登录、登录过期等，需要跳转到登录页
            if (response.status === 401) {
                localStorage.removeItem('token');
                location.reload()
            }
            return Promise.reject(new Error(response.statusText || 'Error'))
        }

        const res = response.data
        // 验证码专用
        if (res.status == 'success') {
            return res
        }
        // 响应成功
        if (res) {
            return res
        }
        return Promise.reject(new Error(res.msg || 'Error'))
    },
    (error: any) => {
        hideLoading();
        console.log('error：', Object.values(error));
        if (error.response.status == 429) {
            ElMessage.error('请求太频繁，请稍后再试');
            return Promise.reject(error)
        }
        if (error.response.status == 422) {
            const errors: any = error.response.data.errors;
            ElMessage.error(Object.values(errors).join('、'));
            return Promise.reject(error)
        }
        if (error.response.status == 401) {
            localStorage.removeItem('token');
            location.reload()
        }
        ElMessage.error(error.message)
        return Promise.reject(error)
    }
)

// 导出 axios 实例
export default service
